package com.shj.controller;

import com.shj.entity.SysArea;
import com.shj.entity.SysInstitution;
import com.shj.service.SysAreaService;
import com.shj.service.SysInstitutionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author songhuajian
 * @Description: TODO
 * @date 2020/5/11 16:08
 **/
@Controller("SysInstitutionController")
@RequestMapping("/system/institution")
public class SysInstitutionController {
    @Autowired
    private SysInstitutionService sysInstitutionService;
    @Autowired
    private SysAreaService sysAreaService;

    @RequestMapping("/find")
    public String findAll(Model model) {
        List<SysInstitution> list = sysInstitutionService.findAll();
        model.addAttribute("list", list);
        return "institution/institution_list";
    }

    @RequestMapping("/openAdd")
    public String openAdd(Model model) {
        // 查找级别在1到2的行政区域
        List<SysArea> list = sysAreaService.findByGrade(1, 2);
        model.addAttribute("list", list);
        return "institution/institution_add";
    }

    @RequestMapping("/add")
    public String add(Model model, SysInstitution sysInstitution) {
        int grade = sysInstitution.getAreaCode().length() == 6 ? 1 : 2;
        sysInstitution.setGrade(grade);
        sysInstitutionService.add(sysInstitution);
        return findAll(model);
    }

    @RequestMapping("/openEdit")
    public String openEdit(Model model, String code) {
        SysInstitution sysInstitution = sysInstitutionService.findByAreaCode(code);
        model.addAttribute("ins", sysInstitution);
        return "institution/institution_edit";
    }

    @RequestMapping("/edit")
    public String edit(Model model, SysInstitution sysInstitution) {
        sysInstitutionService.edit(sysInstitution);
        return findAll(model);
    }

    @RequestMapping("/delete")
    public String delete(Model model, String code) {
        sysInstitutionService.delete(code);
        return findAll(model);
    }
}
